<template>
  <div class="app-container">
    <h2>设备列表</h2>
    <el-row :gutter="20">
      <el-col :span="24" style="margin-bottom: 20px;">
        <el-button type="primary" @click="openAddDeviceDialog">添加设备</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col v-for="device in deviceList" :key="device.deviceId" :span="8" style="margin-bottom: 20px;">
        <el-card>
          <div slot="header" class="clearfix card-header">
            <img :src="windTurbineIcon" alt="风力发电机" class="header-icon">
            <span>{{ device.deviceName }} (ID: {{ device.deviceId }})</span>
          </div>
          <div class="device-details">
            <el-descriptions title="基本信息" :column="2" border>
              <el-descriptions-item label="设备类型">
                <img :src="deviceTypeIcon" alt="设备类型" class="info-icon">{{ device.deviceType }}
              </el-descriptions-item>
              <el-descriptions-item label="型号">
                 <img :src="modelNumberIcon" alt="型号" class="info-icon">{{ device.modelNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="所属区域">
                 <img :src="areaNameIcon" alt="所属区域" class="info-icon">{{ device.areaName || 'N/A' }}
              </el-descriptions-item>
               <el-descriptions-item label="状态">
                  <img :src="statusIcon" alt="状态" class="info-icon">
                  <el-tag :type="getStatusTagType(device.status)">{{ getStatusText(device.status) }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>

             <el-descriptions title="技术参数" :column="2" border style="margin-top: 20px;">
               <el-descriptions-item label="额定功率">
                 <img :src="ratedPowerIcon" alt="额定功率" class="info-icon">{{ device.ratedPower }} KW
               </el-descriptions-item>
               <el-descriptions-item label="叶片长度">
                 <img :src="bladeLengthIcon" alt="叶片长度" class="info-icon">{{ device.bladeLength }} 米
               </el-descriptions-item>
               <el-descriptions-item label="塔筒高度">
                 <img :src="towerHeightIcon" alt="塔筒高度" class="info-icon">{{ device.towerHeight }} 米
               </el-descriptions-item>
             </el-descriptions>

             <el-descriptions title="生产与安装" :column="2" border style="margin-top: 20px;">
               <el-descriptions-item label="生产日期">
                  <img :src="productionDateIcon" alt="生产日期" class="info-icon">{{ device.productionDate }}
               </el-descriptions-item>
                <el-descriptions-item label="购买日期">
                  <img :src="purchaseDateIcon" alt="购买日期" class="info-icon">{{ device.purchaseDate }}
               </el-descriptions-item>
               <el-descriptions-item label="质保期">
                 <img :src="warrantyPeriodIcon" alt="质保期" class="info-icon">{{ device.warrantyPeriod }}个月
               </el-descriptions-item>
               <el-descriptions-item label="安装时间">
                 <img :src="installTimeIcon" alt="安装时间" class="info-icon">{{ formatDate(device.installTime) }}
               </el-descriptions-item>
             </el-descriptions>

          </div>
          <div style="margin-top: 20px; text-align: right;">
            <el-button type="primary" size="small" @click="viewRuntimeData(device.deviceId)">查看运行时数据</el-button>
            <el-button type="danger" size="small" @click="handleDeleteDevice(device.deviceId)">删除设备</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Add Device Dialog -->
    <el-dialog title="添加新设备" v-model="dialogVisible" width="1000px">
      <el-form ref="newDeviceFormRef" :model="newDeviceForm" :rules="newDeviceRules" label-width="150px">

        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="deviceName">
              <template #label>
                <div class="form-item-label-content">
                   <img :src="deviceNameIcon" alt="设备名称" class="info-icon">设备名称
                </div>
              </template>
              <el-input v-model="newDeviceForm.deviceName" placeholder="请输入设备名称"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item prop="deviceType">
              <template #label>
                 <div class="form-item-label-content">
                   <img :src="deviceTypeIcon" alt="设备类型" class="info-icon">设备类型
                 </div>
              </template>
               <el-input v-model="newDeviceForm.deviceType" placeholder="请输入设备类型"></el-input>
            </el-form-item>
           </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item prop="modelNumber">
               <template #label>
                 <div class="form-item-label-content">
                   <img :src="modelNumberIcon" alt="型号" class="info-icon">型号
                 </div>
              </template>
               <el-input v-model="newDeviceForm.modelNumber" placeholder="请输入型号"></el-input>
            </el-form-item>
           </el-col>
            <el-col :span="12">
              <el-form-item prop="status">
                 <template #label>
                   <div class="form-item-label-content">
                    <img :src="statusIcon" alt="状态" class="info-icon">状态
                   </div>
                </template>
                <el-select v-model="newDeviceForm.status" placeholder="请选择状态" style="width: 100%;">
                   <el-option label="停用" :value="0"></el-option>
                   <el-option label="启用" :value="1"></el-option>
                   <el-option label="维修中" :value="2"></el-option>
                   <el-option label="报废" :value="3"></el-option>
                 </el-select>
             </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item prop="currentAreaId">
                <template #label>
                   <div class="form-item-label-content">
                     <img :src="areaNameIcon" alt="所属区域" class="info-icon">所属区域
                   </div>
                </template>
                <el-select v-model="newDeviceForm.currentAreaId" placeholder="请选择所属区域" style="width: 100%;">
                  <el-option
                    v-for="area in areaList"
                    :key="area.areaId"
                    :label="area.areaName"
                    :value="area.areaId"
                  ></el-option>
                </el-select>
            </el-form-item>
           </el-col>
           <!-- Empty col for spacing if needed, or just end the row -->
            <el-col :span="12"></el-col>
         </el-row>


         <el-divider content-position="left">技术参数</el-divider>
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item prop="ratedPower">
                <template #label>
                  <div class="form-item-label-content">
                   <img :src="ratedPowerIcon" alt="额定功率" class="info-icon">额定功率 (KW)
                  </div>
                </template>
               <el-input-number v-model="newDeviceForm.ratedPower" :min="0" :precision="2" placeholder="请输入额定功率" controls-position="right" style="width: 100%;"></el-input-number>
            </el-form-item>
           </el-col>
            <el-col :span="12">
             <el-form-item prop="bladeLength">
               <template #label>
                  <div class="form-item-label-content">
                    <img :src="bladeLengthIcon" alt="叶片长度" class="info-icon">叶片长度 (米)
                  </div>
              </template>
               <el-input-number v-model="newDeviceForm.bladeLength" :min="0" :precision="2" placeholder="请输入叶片长度" controls-position="right" style="width: 100%;"></el-input-number>
            </el-form-item>
           </el-col>
        </el-row>

         <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="towerHeight">
                 <template #label>
                   <div class="form-item-label-content">
                    <img :src="towerHeightIcon" alt="塔筒高度" class="info-icon">塔筒高度 (米)
                   </div>
                </template>
                <el-input-number v-model="newDeviceForm.towerHeight" :min="0" :precision="2" placeholder="请输入塔筒高度" controls-position="right" style="width: 100%;"></el-input-number>
             </el-form-item>
            </el-col>
             <!-- Empty col for spacing if needed -->
            <el-col :span="12"></el-col>
        </el-row>


         <el-divider content-position="left">生产与安装</el-divider>
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item prop="productionDate">
                <template #label>
                   <div class="form-item-label-content">
                     <img :src="productionDateIcon" alt="生产日期" class="info-icon">生产日期
                   </div>
                </template>
                <el-date-picker v-model="newDeviceForm.productionDate" type="date" placeholder="选择生产日期" style="width: 100%;"></el-date-picker>
             </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item prop="purchaseDate">
               <template #label>
                  <div class="form-item-label-content">
                    <img :src="purchaseDateIcon" alt="购买日期" class="info-icon">购买日期
                  </div>
              </template>
              <el-date-picker v-model="newDeviceForm.purchaseDate" type="date" placeholder="选择购买日期" style="width: 100%;"></el-date-picker>
            </el-form-item>
           </el-col>
        </el-row>

         <el-row :gutter="20">
            <el-col :span="12">
             <el-form-item prop="warrantyPeriod">
               <template #label>
                  <div class="form-item-label-content">
                     <img :src="warrantyPeriodIcon" alt="质保期" class="info-icon">质保期 (月)
                  </div>
              </template>
               <el-input-number v-model="newDeviceForm.warrantyPeriod" :min="0" placeholder="请输入质保期" controls-position="right" style="width: 100%;"></el-input-number>
            </el-form-item>
           </el-col>
             <el-col :span="12">
             <el-form-item prop="installTime">
                <template #label>
                   <div class="form-item-label-content">
                    <img :src="installTimeIcon" alt="安装时间" class="info-icon">安装时间
                   </div>
                </template>
               <el-date-picker v-model="newDeviceForm.installTime" type="datetime" placeholder="选择安装时间" style="width: 100%;"></el-date-picker>
            </el-form-item>
           </el-col>
         </el-row>

         <el-divider content-position="left">其他</el-divider>
         <el-row :gutter="20">
            <el-col :span="24">
             <el-form-item label="备注" prop="remark">
                <template #label>
                  <div class="form-item-label-content">
                     <!-- Consider adding a remark icon if available -->
                     备注
                  </div>
                </template>
               <el-input v-model="newDeviceForm.remark" type="textarea" placeholder="请输入备注 (可选)"></el-input>
            </el-form-item>
            </el-col>
         </el-row>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAddDeviceForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getDeviceList, addDevice, delDevice } from '@/api/device/information';
import { getAreaInfoList } from '@/api/device/region';
import { ElTag, ElDescriptions, ElDescriptionsItem, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElDatePicker, ElInputNumber, ElMessage, ElRow, ElCol, ElDivider, ElMessageBox } from 'element-plus';

// Import icons
import installTimeIcon from '@/assets/device/安装时间.png';
import areaNameIcon from '@/assets/device/所属区域.png';
import statusIcon from '@/assets/device/系统状态.png';
import towerHeightIcon from '@/assets/device/高度.png';
import bladeLengthIcon from '@/assets/device/叶片.png';
import ratedPowerIcon from '@/assets/device/额定功率.png';
import warrantyPeriodIcon from '@/assets/device/质保期报修.png';
import purchaseDateIcon from '@/assets/device/购买日期.png';
import productionDateIcon from '@/assets/device/生产日期.png';
import modelNumberIcon from '@/assets/device/型号.png';
import deviceTypeIcon from '@/assets/device/设备类型.png';
import windTurbineIcon from '@/assets/device/风力发电机.png';
import deviceNameIcon from '@/assets/device/风力发电机.png';

const deviceList = ref([]);
const router = useRouter();
const dialogVisible = ref(false);

const newDeviceFormRef = ref(null);
const newDeviceForm = ref({
  deviceName: '',
  deviceType: '',
  modelNumber: '',
  productionDate: null,
  purchaseDate: null,
  warrantyPeriod: 0,
  ratedPower: 0,
  bladeLength: 0,
  towerHeight: 0,
  status: 1,
  currentAreaId: null,
  installTime: null,
  remark: ''
});

const newDeviceRules = ref({
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  deviceType: [{ required: true, message: '请输入设备类型', trigger: 'blur' }],
  modelNumber: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  productionDate: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
  purchaseDate: [{ required: true, message: '请选择购买日期', trigger: 'change' }],
  warrantyPeriod: [{ required: true, message: '请输入质保期', trigger: 'blur' }],
  ratedPower: [{ required: true, message: '请输入额定功率', trigger: 'blur' }],
  bladeLength: [{ required: true, message: '请输入叶片长度', trigger: 'blur' }],
  towerHeight: [{ required: true, message: '请输入塔筒高度', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  currentAreaId: [{ required: false, message: '请选择所属区域', trigger: 'change' }],
  installTime: [{ required: true, message: '请选择安装时间', trigger: 'change' }],
});

const areaList = ref([]);

const fetchDeviceList = () => {
  getDeviceList().then(response => {
    if (response.code === 200) {
      deviceList.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取设备列表失败');
      deviceList.value = [];
    }
  }).catch(error => {
    console.error("Failed to fetch device list:", error);
    // Optionally display an error message to the user
  });
};

// Method to fetch area list
const fetchAreaList = async () => {
  try {
    const response = await getAreaInfoList();
    // Assuming the API returns an array of area objects with 'areaId' and 'areaName'
    areaList.value = response.data || response; // Adjust based on actual API response structure
  } catch (error) {
    console.error("Failed to fetch area list:", error);
    ElMessage.error('获取区域列表失败');
  }
};

const viewRuntimeData = (deviceId) => {
  router.push(`/device/runtime-data/${deviceId}`);
};

// Method to format date string (only date)
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  return `${year}-${month}-${day}`;
};

// Method to get status text
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '停用';
    case 1:
      return '启用';
    case 2:
      return '维修中';
    case 3:
      return '报废';
    default:
      return '未知';
  }
};

// Method to get status tag type (color)
const getStatusTagType = (status) => {
  switch (status) {
    case 0:
       return 'info';
    case 1:
      return 'success';
    case 2:
      return 'warning';
    case 3:
      return 'danger';
    default:
      return 'info';
  }
};

// Method to open the add device dialog and reset form
const openAddDeviceDialog = () => {
  dialogVisible.value = true;
  // Reset form when dialog opens
  if (newDeviceFormRef.value) {
    newDeviceFormRef.value.resetFields();
     newDeviceForm.value = { // Reset to initial state
      deviceName: '',
      deviceType: '',
      modelNumber: '',
      productionDate: null,
      purchaseDate: null,
      warrantyPeriod: 0,
      ratedPower: 0,
      bladeLength: 0,
      towerHeight: 0,
      status: 1,
      currentAreaId: null,
      installTime: null,
      remark: ''
    };
  }
  // Fetch area list when dialog opens if not already fetched
  if (areaList.value.length === 0) {
    fetchAreaList();
  }
};

// Method to handle form submission
const submitAddDeviceForm = () => {
  newDeviceFormRef.value.validate(async (valid) => {
    if (valid) {
      // Form is valid, call the API
      try {
        const submissionForm = {
          ...newDeviceForm.value,
          productionDate: newDeviceForm.value.productionDate ? new Date(newDeviceForm.value.productionDate).toISOString() : null,
          purchaseDate: newDeviceForm.value.purchaseDate ? new Date(newDeviceForm.value.purchaseDate).toISOString() : null,
          installTime: newDeviceForm.value.installTime ? new Date(newDeviceForm.value.installTime).toISOString() : null,
           // currentAreaId is already the correct type (Number or null) from el-select
        };

        const response = await addDevice(submissionForm);
        if (response && response.code === 200) {
          ElMessage.success('设备添加成功');
          dialogVisible.value = false; // Close the dialog
          fetchDeviceList(); // Refresh the device list
        } else {
           ElMessage.error(response.msg || '设备添加失败');
        }
      } catch (error) {
        console.error("Failed to add device:", error);
        ElMessage.error('设备添加失败');
      }
    } else {
      console.log('Form validation failed');
      ElMessage.warning('请检查表单填写项');
      return false;
    }
  });
};

// Method to handle device deletion
const handleDeleteDevice = (deviceId) => {
  ElMessageBox.confirm(
    '确定要删除该设备吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDevice(deviceId).then(response => {
      if (response.code === 200) {
        ElMessage.success('设备删除成功');
        fetchDeviceList(); // Refresh the list
      } else {
        ElMessage.error(response.msg || '设备删除失败');
      }
    }).catch(error => {
      console.error("Failed to delete device:", error);
      ElMessage.error('设备删除失败');
    });
  }).catch(() => {
    // User cancelled deletion
    ElMessage.info('已取消删除');
  });
};

onMounted(() => {
  fetchDeviceList();
   fetchAreaList();
});

</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.device-details {
  padding: 0 10px;
}

/* Adjust el-descriptions-item label width if needed */
.el-descriptions-item__label {
  width: 100px;
}

.info-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  vertical-align: middle;
}

.header-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
  vertical-align: middle;
}

/* Adjust tag alignment if needed */
.el-tag {
  vertical-align: middle;
}

/* Remove previous p tag styles as we are using el-descriptions */
/*
.detail-item {
   margin-bottom: 15px;
   display: flex;
   align-items: center;
}

.detail-item strong {
  margin-right: 5px;\n  flex-shrink: 0;
}

.install-time-item .install-time-value {
    white-space: nowrap;
}
*/

.form-item-label-content {
  display: flex;
  align-items: center;
}

</style>
